#include "StdAfx.h"
#include "MICEXTableKey.h"
#include "MICEXTable.h"


MICEXTableKey::MICEXTableKey()
	: pData(0)
{
}

MICEXTableKey::MICEXTableKey(const MICEXTableKey& compKey)
{
	operator=(compKey);
}

MICEXTableKey::MICEXTableKey(MICEXTable* pTable, int nFields, BYTE* pFieldBuf, int32 nDataLen, BYTE* pDataBuf)
{
	this->pTable = pTable;
	Size = pTable->KeySize;
	pData = std::auto_ptr<BYTE>(new BYTE[Size]);

	memset(pData.get(), 0, Size);
	
	//Construct map to remeber offsets  for all fields. Do we need this later?!
	std::map<int32, int32> mapFieldsOffset;

	//In case (nFields == 0) => (pFieldBuf == 0) and pDataBuf contains all fields data
	int32 offset = 0;
	int32 nRealFields = (nFields != 0) ? nFields : pTable->OutputFieldsCount;
	
	for (int nField = 0; nField < nRealFields; nField++)
	{
		int32 nFieldNum = (pFieldBuf != 0) ? pFieldBuf[nField] : nField;

		mapFieldsOffset[nFieldNum]	= offset;

		offset += pTable->OutputFields[nFieldNum].FieldSize;
	}
	
	offset = 0;
	for(UINT nKeyField = 0; nKeyField < pTable->KeyFields.size(); nKeyField++)
	{
		int32 size = pTable->OutputFields[pTable->KeyFields[nKeyField]].FieldSize;
		BYTE* pVal = (pDataBuf + mapFieldsOffset[pTable->KeyFields[nKeyField]]);
		memcpy((pData.get() + offset), pVal, size);
		offset += pTable->OutputFields[pTable->KeyFields[nKeyField]].FieldSize;
	}
}

MICEXTableKey::~MICEXTableKey()
{
}